package com.pzl.util;

import android.util.Base64;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AESUtil {

    static final String AESTYPE = "AES/ECB/PKCS5Padding";

    //注意: 这里的password(秘钥必须是16位的)
    public static final String KEY = "1234567890123456";

    /**
     * 加密算法
     * @param text
     * @param keyStr
     * @return
     */
    public static String encrypt(String text, String keyStr) {
        byte[] encrypt = null;
        try {
            Key key = generateKey(keyStr);
            Cipher cipher = Cipher.getInstance(AESTYPE);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            encrypt = cipher.doFinal(text.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encrypt != null ? new String(encodeBASE64(encrypt)) : null;
//        return encodeBASE64(text.getBytes());
    }

    /**
     * 解密算法
     * @param text
     * @param keyStr
     * @return
     */
    public static String decrypt(String text, String keyStr) {
        byte[] decrypt = null;
        try {
            byte[] textByte = decodeBASE64(text);
            Key key = generateKey(keyStr);
            Cipher cipher = Cipher.getInstance(AESTYPE);
            cipher.init(Cipher.DECRYPT_MODE, key);
            decrypt = cipher.doFinal(textByte);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return decrypt != null ? new String(decrypt).trim() : null;
//        return new String(decodeBASE64(text));
    }

    private static Key generateKey(String key) throws Exception {
        try {
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
            return keySpec;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

    }

    /**
     * BASE64解密
     *
     * @param text
     * @return
     */
    @SuppressWarnings("static-access")
    public static byte[] decodeBASE64(String text) {
        return Base64.decode(text.getBytes(), Base64.NO_WRAP);
    }

    /**
     * BASE64加密
     *
     * @param text
     * @return
     * @throws Exception
     */
    @SuppressWarnings("static-access")
    public static String encodeBASE64(byte[] text) {
        return new String(Base64.encode(text, Base64.NO_WRAP));
    }


}
